package com.dzl.config.interceptor;

import com.dzl.config.exception.CommonException;
import com.dzl.util.EmptyUtils;
import com.dzl.util.HttpCode;
import com.dzl.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @Description:登录拦截器
 * @author liufan
 * @time:2021年4月24日 下午3:32:43
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        String contextPath = request.getContextPath();
		String token = request.getHeader("token");
		if(StringUtils.isBlank(token)) {
		    if(EmptyUtils.isNotEmpty(contextPath) && contextPath.equals("/api")){
                throw new CommonException(HttpCode.TOKEN_INVALID);
            }else{
                throw new CommonException(HttpCode.NO_LOGIN);
            }
		}
		Object admin =  RedisUtil.get(token);
		if(null == admin) {
            if(EmptyUtils.isNotEmpty(contextPath) && contextPath.equals("/api")){
                throw new CommonException(HttpCode.TOKEN_INVALID);
            }else{
                throw new CommonException(HttpCode.NO_LOGIN);
            }
		}
		return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
